<template>
  <div class="app-container">
    <el-card>
      <!--用户数据-->
      <el-form :model="queryParams" ref="queryForm" size="small" label-width="80px">
        <el-row>
          <el-col :span="4">
            <el-form-item label="学期名称">
              <el-input v-model.trim="queryParams.name" placeholder="输入内容" clearable @keyup.enter.native="handleQuery"
                @input="getList" />
            </el-form-item>
          </el-col>
          <el-col :span="2">
            <el-form-item>
              <el-button type="primary" icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>

      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
            v-hasPermi="['project:semester:add']">新增</el-button>
        </el-col>
      </el-row>
      <el-table v-loading="loading" :data="tableList" height="440" @sort-change="sortChange">
        <el-table-column label="序号" type="index" width="50" align="center" />
        <el-table-column label="学期名称" align="center" prop="name" />
        <el-table-column label="开始时间" align="center" prop="startTime" sortable="custom">
          <template slot-scope="scope"> {{ scope.row.startTime.slice(0, 10) }} </template>
        </el-table-column>
        <el-table-column label="结束时间" align="center" prop="endTime" sortable="custom">
          <template slot-scope="scope"> {{ scope.row.endTime.slice(0, 10) }} </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="160" class-name="small-padding fixed-width">
          <template slot-scope="scope">
            <el-button type="text" @click="handleUpdate(scope.row)" v-hasPermi="['project:semester:edit']">编辑</el-button>
            <el-button style="color: #f56c6c;" type="text" @click="handleDelete(scope.row)"
              v-hasPermi="['project:semester:remove']">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
        @pagination="getList" />
    </el-card>
    <!-- 添加或修改用户配置对话框 -->
    <el-dialog :title="title" :visible.sync="open" append-to-body width="40%">
      <el-form :model="form" :rules="rules" ref="form" label-width="85px">
        <el-row>
          <el-col :span="24">
            <el-form-item label="学期名称: " prop="value">
              <div style="display: flex;">
                <el-select v-model="beginValue" placeholder="请选择" @change="changeBegin">
                  <el-option v-for="item in beginList" :key="item" :label="item" :value="item" />
                </el-select>
                <!-- <span class="spanMa"> 年 </span> -->
                <span class="spanMa"> ~ </span>
                <el-select v-model="endValue" placeholder="请选择" @change="changeEnd">
                  <el-option v-for="item in endList" :key="item" :label="item" :value="item" />
                  <!-- <el-option :label="Number(beginValue) + 1" :value="Number(beginValue) + 1" v-if="beginValue" />
                  <el-option :label="Number(beginValue) + 2" :value="Number(beginValue) + 2" v-if="beginValue" /> -->
                </el-select>
                <span class="spanMa"> 学年 </span>
                <span class="spanMa">第</span>
                <el-select v-model="form.value" placeholder="请选择" @change="$forceUpdate()">
                  <el-option label="一" value="一" />
                  <el-option label="二" value="二" />
                </el-select>
                <span class="spanMa">学期</span>
              </div>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="学期时间: " prop="dateValue">
              <el-date-picker v-model="form.dateValue" type="daterange" range-separator="至" start-placeholder="开始时间"
                end-placeholder="结束时间" format="yyyy-MM-dd" value-format="yyyy-MM-dd" @input="$forceUpdate()">
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer" style="text-align: center">
        <el-button @click="cancel">取 消</el-button>
        <el-button type="primary" @click="submitForm">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { projectList, projectAdd, projectPut, projectDele } from "@/api/semesManage";
export default {
  name: "semesManage",
  data() {
    return {
      // 遮罩层
      loading: false,
      // 总条数
      total: 0,
      tableList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,

      // 表单参数
      form: {
        name: ''
      },

      // 表单校验
      rules: {
        value: [
          { required: true, message: '设置有误，请检查', trigger: 'blur' },
        ],
        dateValue: [
          { required: true, message: '请选择学期时间范围', trigger: 'blur' },
          {
            validator: (rule, value, callback) => {
              if (!value || value.length !== 2) {
                callback(new Error('请选择完整的学期时间范围'));
              } else if (new Date(value[0]) >= new Date(value[1])) {
                callback(new Error('开始时间必须早于结束时间'));
              } else {
                callback(); // 校验通过
              }
            },
            trigger: 'blur'
          }
        ],
      },
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
      },
      beginList: ['2020', '2021', '2022', '2023', '2024', '2025', '2026', '2027', '2028', '2029', '2030'],
      endList: [],
      beginValue: "",
      endValue: "",
    };
  },
  watch: {},
  created() {
    this.getList();
  },
  methods: {
    changeBegin(e) {
      this.form.value = '';
      this.endList = [];
      this.endList.push(String(Number(e) + 1));
      this.endValue = this.endList[0];
      if (this.endValue && Number(e) > Number(this.endValue)) {
        this.$message({
          message: "学期开始时间不得大于结束时间",
          type: "warning"
        });
        this.beginValue = '';
        this.$forceUpdate();
        return;
      }
    },
    changeEnd(e) {
      this.form.value = '';
      if (this.beginValue && Number(e) < Number(this.beginValue)) {
        this.$message({
          message: "学期结束时间不得小于开始时间",
          type: "warning"
        });
        this.endValue = '';
        this.$forceUpdate();
        return;
      }
    },
    /** 查询列表 */
    getList() {
      this.loading = true;
      projectList({ ...this.queryParams }).then(res => {
        this.tableList = res.rows;
        this.total = res.total;
        this.loading = false;
      });
    },
    sortChange(row) {
      const sortMap = {
        startTime: 'startTimeSort',
        endTime: 'endTimeSort',
      };
      const getSortOrder = (order) => {
        if (order === 'ascending') return 'asc';
        if (order === 'descending') return 'desc';
        return null;
      };

      const sortField = sortMap[row.prop];
      const sortOrder = getSortOrder(row.order);

      if (sortField) {
        this.queryParams.pageNum = 1;
        this.queryParams.pageSize = 10;
        Object.keys(sortMap).forEach((key) => {
          const oldSortField = sortMap[key];
          if (this.queryParams[oldSortField]) {
            delete this.queryParams[oldSortField];
          }
        })
        this.queryParams[sortField] = sortOrder;
        this.getList();
      }
    },
    handleAdd() {
      this.beginValue = '';
      this.endValue = '';
      this.title = "新增学期";
      this.resetForm("form");
      this.form = {};
      this.open = true;
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.title = "编辑学期";
      this.resetForm("form");
      this.form = { ...row };
      this.form.dateValue = [row.startTime.slice(0, 10), row.endTime.slice(0, 10)];
      this.beginValue = row.name.slice(0, 4);
      this.endValue = row.name.slice(7, 11);
      this.form.value = row.name.slice(15, 16);
      this.$forceUpdate();
      this.open = true;
    },
    cancel() {
      this.open = false;
      this.form = {};
    },

    /** 重置按钮操作 */
    resetQuery() {
      this.queryParams = {
        pageNum: 1,
        pageSize: 10,
      };
      this.resetForm("queryForm");
      this.getList();
    },
    handleDelete(row) {
      this.$modal
        .confirm('是否确认删除"' + row.name + '"数据项？')
        .then(function () {
          return projectDele(row.id);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => { });
    },
    /** 提交按钮 */
    submitForm() {
      const urlType = this.form.id >= 0 ? projectPut : projectAdd;
      const msgType = this.form.id >= 0 ? "编辑成功" : "新增成功";
      this.$refs["form"].validate((valid) => {
        if (valid) {
          this.form.startTime = this.form.dateValue[0] + ' 00:00:00';
          this.form.endTime = this.form.dateValue[1] + ' 23:59:59';
          this.form.name = this.beginValue + " ~ " + this.endValue + "学年 第" + this.form.value + "学期"
          urlType({ ...this.form }).then((res) => {
            if (res.code == 200) {
              this.$modal.msgSuccess(msgType);
              this.form = {};
              this.getList();
              this.open = false;
            }
          })
        }
      })
    },
  },
};
</script>
<style scoped lang="scss">
::v-deep .el-dialog__body {
  .spanMa {
    margin-left: 5px;
    margin-right: 5px;
  }

  .el-select {
    width: 20% !important;
  }

  .el-date-editor {
    width: 80% !important;
  }
}
</style>
